<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="$emit('close')"
    title="数据导入"
    :width="dialogWidth"
    :close-on-click-modal="false"
    class="responsive-dialog"
  >
    <div class="import-container">
      <!-- 导入选项 -->
      <div class="import-options">
        <h4>导入方式</h4>
        <el-radio-group v-model="importType" @change="resetImport">
          <el-radio label="file">从文件导入</el-radio>
          <el-radio label="text">从文本导入</el-radio>
        </el-radio-group>
      </div>

      <!-- 文件导入 -->
      <div v-if="importType === 'file'" class="file-import">
        <el-upload
          ref="uploadRef"
          class="upload-demo"
          drag
          :auto-upload="false"
          :on-change="handleFileChange"
          :file-list="fileList"
          accept=".json,.csv,.txt,.xml,.html,.yaml,.yml"
          :limit="1"
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            将文件拖到此处，或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              支持格式：JSON, CSV, TXT, XML, HTML, YAML (最大 10MB)
            </div>
          </template>
        </el-upload>
      </div>

      <!-- 文本导入 -->
      <div v-if="importType === 'text'" class="text-import">
        <div class="format-selector">
          <label>文本格式：</label>
          <el-select v-model="textFormat" placeholder="选择格式">
            <el-option label="JSON" value="json" />
            <el-option label="CSV" value="csv" />
            <el-option label="YAML" value="yaml" />
          </el-select>
        </div>
        <el-input
          v-model="importText"
          type="textarea"
          :rows="10"
          placeholder="请粘贴要导入的数据..."
        />
      </div>

      <!-- 导入设置 -->
      <div v-if="parsedData.length > 0" class="import-settings">
        <h4>导入设置</h4>
        <div class="settings-grid">
          <div class="setting-item">
            <el-checkbox v-model="importOptions.skipDuplicates">
              跳过重复项
            </el-checkbox>
            <div class="setting-desc">基于名称和用户名判断重复</div>
          </div>
          <div class="setting-item">
            <el-checkbox v-model="importOptions.backupBeforeImport">
              导入前备份
            </el-checkbox>
            <div class="setting-desc">自动创建当前数据备份</div>
          </div>
          <div class="setting-item">
            <el-checkbox v-model="importOptions.mergeCategories">
              合并分类
            </el-checkbox>
            <div class="setting-desc">保留现有分类并添加新分类</div>
          </div>
        </div>
      </div>

      <!-- 数据预览 -->
      <div v-if="parsedData.length > 0" class="data-preview">
        <div class="preview-header">
          <h4>数据预览</h4>
          <div class="preview-stats">
            <span>共 {{ parsedData.length }} 条记录</span>
            <span v-if="duplicateCount > 0" class="duplicate-warning">
              ({{ duplicateCount }} 条重复)
            </span>
          </div>
        </div>
        
        <div class="preview-table">
          <el-table
            :data="previewData"
            style="width: 100%"
            max-height="300"
            size="small"
          >
            <el-table-column prop="name" label="名称" width="120" />
            <el-table-column prop="username" label="用户名" width="120" />
            <el-table-column prop="category" label="分类" width="100" />
            <el-table-column prop="url" label="网址" width="150" />
            <el-table-column label="状态" width="80">
              <template #default="scope">
                <el-tag v-if="scope.row.isDuplicate" type="warning" size="small">
                  重复
                </el-tag>
                <el-tag v-else type="success" size="small">
                  新增
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <!-- 错误信息 -->
      <div v-if="parseError" class="error-info">
        <el-alert
          title="解析错误"
          :description="parseError"
          type="error"
          :closable="false"
        />
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="$emit('close')">取消</el-button>
        <el-button 
          type="primary" 
          @click="performImport"
          :disabled="!canImport"
          :loading="isImporting"
        >
          {{ isImporting ? '导入中...' : `导入 ${parsedData.length} 条记录` }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useAccountsStore } from '../stores/accounts'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['close', 'imported'])

const accountsStore = useAccountsStore()
const uploadRef = ref()
const importType = ref('file')
const textFormat = ref('json')
const importText = ref('')
const fileList = ref([])
const parsedData = ref([])
const parseError = ref('')
const isImporting = ref(false)

const importOptions = ref({
  skipDuplicates: true,
  backupBeforeImport: true,
  mergeCategories: true
})

// 响应式dialog宽度
const dialogWidth = computed(() => {
  if (typeof window !== 'undefined') {
    const windowWidth = window.innerWidth
    if (windowWidth < 768) return '95%'
    if (windowWidth < 1024) return '85%'
    if (windowWidth < 1400) return '75%'
    return '700px'
  }
  return '700px'
})

// 预览数据 (限制显示数量)
const previewData = computed(() => {
  return parsedData.value.slice(0, 50) // 只显示前50条
})

// 重复记录数量
const duplicateCount = computed(() => {
  return parsedData.value.filter(item => item.isDuplicate).length
})

// 是否可以导入
const canImport = computed(() => {
  return parsedData.value.length > 0 && !parseError.value
})

// 重置导入状态
const resetImport = () => {
  parsedData.value = []
  parseError.value = ''
  fileList.value = []
  importText.value = ''
}

// 处理文件变化
const handleFileChange = (file) => {
  parseError.value = ''
  
  if (file.size > 10 * 1024 * 1024) { // 10MB限制
    parseError.value = '文件大小不能超过 10MB'
    return
  }
  
  const reader = new FileReader()
  reader.onload = (e) => {
    try {
      const content = e.target.result
      const format = getFileFormat(file.name)
      parseData(content, format)
    } catch (error) {
      parseError.value = '文件读取失败：' + error.message
    }
  }
  reader.readAsText(file.raw)
}

// 获取文件格式
const getFileFormat = (filename) => {
  const ext = filename.split('.').pop().toLowerCase()
  const formatMap = {
    'json': 'json',
    'csv': 'csv',
    'txt': 'txt',
    'xml': 'xml',
    'html': 'html',
    'yaml': 'yaml',
    'yml': 'yaml'
  }
  return formatMap[ext] || 'json'
}

// 解析数据
const parseData = (content, format) => {
  try {
    let data = []
    
    switch (format) {
      case 'json':
        data = parseJSON(content)
        break
      case 'csv':
        data = parseCSV(content)
        break
      case 'txt':
        data = parseTXT(content)
        break
      case 'xml':
        data = parseXML(content)
        break
      case 'html':
        data = parseHTML(content)
        break
      case 'yaml':
        data = parseYAML(content)
        break
    }
    
    // 标记重复项
    data = markDuplicates(data)
    parsedData.value = data
    parseError.value = ''
    
  } catch (error) {
    parseError.value = `${format.toUpperCase()} 解析失败: ${error.message}`
    parsedData.value = []
  }
}

// 解析JSON
const parseJSON = (content) => {
  const data = JSON.parse(content)
  
  // 尝试不同的JSON结构
  if (data.accounts && Array.isArray(data.accounts)) {
    return data.accounts
  } else if (Array.isArray(data)) {
    return data
  } else {
    throw new Error('无效的JSON格式，需要包含accounts数组')
  }
}

// 解析CSV
const parseCSV = (content) => {
  const lines = content.split('\n').filter(line => line.trim())
  if (lines.length < 2) throw new Error('CSV文件至少需要标题行和数据行')
  
  const headers = lines[0].split(',').map(h => h.trim().replace(/"/g, ''))
  const data = []
  
  for (let i = 1; i < lines.length; i++) {
    const values = parseCSVLine(lines[i])
    if (values.length === headers.length) {
      const item = {}
      headers.forEach((header, index) => {
        const mappedKey = mapCSVHeader(header)
        if (mappedKey) {
          item[mappedKey] = values[index]
        }
      })
      
      // 基本验证
      if (item.name && item.username) {
        data.push(standardizeAccount(item))
      }
    }
  }
  
  return data
}

// 解析CSV行
const parseCSVLine = (line) => {
  const values = []
  let current = ''
  let inQuotes = false
  
  for (let i = 0; i < line.length; i++) {
    const char = line[i]
    
    if (char === '"') {
      inQuotes = !inQuotes
    } else if (char === ',' && !inQuotes) {
      values.push(current.trim())
      current = ''
    } else {
      current += char
    }
  }
  
  values.push(current.trim())
  return values
}

// 映射CSV标题
const mapCSVHeader = (header) => {
  const mapping = {
    '名称': 'name',
    'name': 'name',
    'title': 'name',
    '用户名': 'username',
    'username': 'username',
    'user': 'username',
    '密码': 'password',
    'password': 'password',
    'pass': 'password',
    '网址': 'url',
    'url': 'url',
    'website': 'url',
    '分类': 'category',
    'category': 'category',
    'type': 'category',
    '备注': 'notes',
    'notes': 'notes',
    'note': 'notes',
    'description': 'notes'
  }
  
  return mapping[header.toLowerCase()]
}

// 解析纯文本 (简单格式)
const parseTXT = (content) => {
  const data = []
  const lines = content.split('\n')
  let currentAccount = {}
  
  for (const line of lines) {
    const trimmed = line.trim()
    if (!trimmed) continue
    
    if (trimmed.startsWith('===') || trimmed.startsWith('---')) {
      if (currentAccount.name && currentAccount.username) {
        data.push(standardizeAccount(currentAccount))
      }
      currentAccount = {}
    } else if (trimmed.includes(':')) {
      const [key, value] = trimmed.split(':').map(s => s.trim())
      const mappedKey = mapTXTKey(key)
      if (mappedKey && value) {
        currentAccount[mappedKey] = value
      }
    }
  }
  
  // 添加最后一个账号
  if (currentAccount.name && currentAccount.username) {
    data.push(standardizeAccount(currentAccount))
  }
  
  return data
}

// 映射TXT键名
const mapTXTKey = (key) => {
  const mapping = {
    '名称': 'name',
    '用户名': 'username',
    '密码': 'password',
    '网址': 'url',
    '分类': 'category',
    '备注': 'notes'
  }
  
  return mapping[key] || key.toLowerCase()
}

// 简单的XML解析
const parseXML = (content) => {
  // 这里实现一个简单的XML解析器
  const data = []
  const accountMatches = content.match(/<account>([\s\S]*?)<\/account>/g)
  
  if (!accountMatches) throw new Error('未找到有效的账号数据')
  
  for (const match of accountMatches) {
    const account = {}
    const fields = ['name', 'username', 'password', 'url', 'category', 'notes']
    
    for (const field of fields) {
      const regex = new RegExp(`<${field}>(.*?)<\/${field}>`, 's')
      const fieldMatch = match.match(regex)
      if (fieldMatch) {
        account[field] = fieldMatch[1].trim()
      }
    }
    
    if (account.name && account.username) {
      data.push(standardizeAccount(account))
    }
  }
  
  return data
}

// 简单的HTML解析
const parseHTML = (content) => {
  // 从HTML表格中提取数据
  const data = []
  const tableMatch = content.match(/<table[\s\S]*?<\/table>/i)
  
  if (!tableMatch) throw new Error('未找到HTML表格')
  
  const rowMatches = tableMatch[0].match(/<tr[\s\S]*?<\/tr>/gi)
  if (!rowMatches || rowMatches.length < 2) throw new Error('表格数据不足')
  
  // 解析表头
  const headerMatch = rowMatches[0].match(/<th[\s\S]*?>(.*?)<\/th>/gi)
  const headers = headerMatch ? headerMatch.map(h => h.replace(/<[^>]*>/g, '').trim()) : []
  
  // 解析数据行
  for (let i = 1; i < rowMatches.length; i++) {
    const cellMatches = rowMatches[i].match(/<td[\s\S]*?>(.*?)<\/td>/gi)
    if (cellMatches && cellMatches.length === headers.length) {
      const values = cellMatches.map(c => c.replace(/<[^>]*>/g, '').trim())
      const account = {}
      
      headers.forEach((header, index) => {
        const mappedKey = mapCSVHeader(header)
        if (mappedKey && values[index]) {
          account[mappedKey] = values[index]
        }
      })
      
      if (account.name && account.username) {
        data.push(standardizeAccount(account))
      }
    }
  }
  
  return data
}

// 简单的YAML解析
const parseYAML = (content) => {
  // 简单的YAML解析实现
  const data = []
  const lines = content.split('\n')
  let currentAccount = null
  let inAccounts = false
  
  for (const line of lines) {
    const trimmed = line.trim()
    
    if (trimmed === 'accounts:') {
      inAccounts = true
      continue
    }
    
    if (inAccounts) {
      if (trimmed.startsWith('- ') || trimmed.startsWith('  - ')) {
        if (currentAccount && currentAccount.name && currentAccount.username) {
          data.push(standardizeAccount(currentAccount))
        }
        currentAccount = {}
        
        // 解析内联属性
        const inlineMatch = trimmed.match(/- (.+)/)
        if (inlineMatch) {
          const parts = inlineMatch[1].split(':')
          if (parts.length === 2) {
            const key = parts[0].trim()
            const value = parts[1].trim().replace(/"/g, '')
            currentAccount[key] = value
          }
        }
      } else if (trimmed.includes(':') && currentAccount) {
        const [key, value] = trimmed.split(':').map(s => s.trim())
        if (value) {
          currentAccount[key] = value.replace(/"/g, '')
        }
      }
    }
  }
  
  // 添加最后一个账号
  if (currentAccount && currentAccount.name && currentAccount.username) {
    data.push(standardizeAccount(currentAccount))
  }
  
  return data
}

// 标准化账号数据
const standardizeAccount = (account) => {
  return {
    id: account.id || `import_${Date.now()}_${Math.random()}`,
    name: account.name || '',
    username: account.username || '',
    password: account.password || '',
    url: account.url || '',
    category: account.category || '工作',
    notes: account.notes || '',
    isFavorite: account.isFavorite === 'true' || account.isFavorite === true,
    createdAt: account.createdAt || new Date().toISOString(),
    updatedAt: account.updatedAt || new Date().toISOString()
  }
}

// 标记重复项
const markDuplicates = (data) => {
  const existing = accountsStore.accounts
  
  return data.map(item => {
    const isDuplicate = existing.some(account => 
      account.name === item.name && account.username === item.username
    )
    
    return { ...item, isDuplicate }
  })
}

// 执行导入
const performImport = async () => {
  try {
    isImporting.value = true
    
    // 导入前备份
    if (importOptions.value.backupBeforeImport) {
      await createBackup()
    }
    
    let importData = [...parsedData.value]
    
    // 跳过重复项
    if (importOptions.value.skipDuplicates) {
      importData = importData.filter(item => !item.isDuplicate)
    }
    
    // 导入数据
    let successCount = 0
    for (const account of importData) {
      try {
        await accountsStore.addAccount(account)
        successCount++
      } catch (error) {
        console.error('导入账号失败:', error)
      }
    }
    
    ElMessage.success(`成功导入 ${successCount} 条记录`)
    emit('imported', successCount)
    emit('close')
    
  } catch (error) {
    console.error('导入失败:', error)
    ElMessage.error('导入失败：' + error.message)
  } finally {
    isImporting.value = false
  }
}

// 创建备份
const createBackup = async () => {
  try {
    const backupData = {
      backupInfo: {
        date: new Date().toISOString(),
        type: 'auto_backup_before_import',
        reason: 'Auto backup before data import'
      },
      accounts: accountsStore.accounts
    }
    
    const blob = new Blob([JSON.stringify(backupData, null, 2)], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `import_backup_${new Date().toISOString().split('T')[0]}.json`
    a.click()
    URL.revokeObjectURL(url)
    
  } catch (error) {
    console.error('备份失败:', error)
  }
}

// 监听文本输入变化
watch([importText, textFormat], () => {
  if (importText.value.trim()) {
    parseData(importText.value, textFormat.value)
  } else {
    parsedData.value = []
    parseError.value = ''
  }
})

// 重置组件状态
watch(() => props.visible, (visible) => {
  if (visible) {
    resetImport()
  }
})
</script>

<style scoped>
.responsive-dialog {
  --el-dialog-padding-primary: clamp(12px, 2vw, 20px);
}

.import-container {
  display: flex;
  flex-direction: column;
  gap: clamp(16px, 3vw, 24px);
  padding: var(--el-dialog-padding-primary);
  max-height: 70vh;
  overflow-y: auto;
}

.import-container h4 {
  margin: 0 0 clamp(12px, 2vw, 16px) 0;
  color: #333;
  font-size: clamp(14px, 2.5vw, 16px);
  font-weight: 600;
}

.import-options {
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.file-import {
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
}

.text-import {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.format-selector {
  display: flex;
  align-items: center;
  gap: 12px;
}

.format-selector label {
  font-weight: 500;
  color: #333;
}

.import-settings {
  padding: 16px;
  background: #f0f9ff;
  border: 1px solid #bfdbfe;
  border-radius: 8px;
}

.settings-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.setting-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.setting-desc {
  font-size: 12px;
  color: #666;
  margin-left: 24px;
}

.data-preview {
  border: 1px solid #e6e6e6;
  border-radius: 8px;
  overflow: hidden;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: #f8f9fa;
  border-bottom: 1px solid #e6e6e6;
}

.preview-header h4 {
  margin: 0;
}

.preview-stats {
  display: flex;
  gap: 12px;
  font-size: 14px;
  color: #666;
}

.duplicate-warning {
  color: #e6a23c;
  font-weight: 500;
}

.preview-table {
  padding: 16px;
}

.error-info {
  margin-top: 16px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: clamp(8px, 1.5vw, 12px);
  padding: var(--el-dialog-padding-primary);
  flex-wrap: wrap;
}

/* 移动端优化 */
@media (max-width: 768px) {
  .settings-grid {
    grid-template-columns: 1fr;
  }
  
  .preview-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .preview-stats {
    flex-direction: column;
    gap: 4px;
  }
  
  .dialog-footer {
    flex-direction: column-reverse;
  }
  
  .dialog-footer .el-button {
    width: 100%;
  }
}

/* 小屏幕优化 */
@media (max-width: 480px) {
  .import-container {
    padding: 8px;
    gap: 12px;
  }
  
  .import-options,
  .import-settings,
  .export-preview {
    padding: 8px;
  }
}
</style>
